package api;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 1.获取到用户名和密码.
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {
            String html = "<h3>登录失败! 缺少用户名或者密码! </h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        // 2.读取数据库, 是否和数据库中的匹配.
        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if (user == null) {
            String html = "<h3>用户名或密码错误! </h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        if (!password.equals(user.getPassword())) {
            String html = "<h3>用户名或密码错误! </h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        // 3.用户名和密码都正确,需要设置会话
        //创建出一个会话
        HttpSession session = req.getSession(true);
        //把用户对象存储到session中,下次用户访问其他页面,就可以直接拿到会话 进一步拿到之前的user对象
        session.setAttribute("user", user);
        // 4.返回一个重定向响应, 能够跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    //判定用户的登录状态,已登录返回200,未登录返回403
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //看当前请求是否已经存在会话. 并且当前的会话是否包含user对象.
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        //200是默认的状态码, 此处不写也可以
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        user.setPassword(""); //避免把密码也返回给前端
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}